new Vue({
    el: '#app',
    data() {
        return {
            socketTask: null,//websocket服务器
            is_open_socket: false,//判断websocket服务器是否开启
            user: [],
            //存放用户信息和与用户聊天记录
            masseg: '',//发送的消息
            user2: [
            ],
            isShow: true,
            index: 0,
        }
    },
    mounted() {
        // this.getChatRecords();
        this.connectWebsocket();
        window.addEventListener('unload', function () {
            // 页面关闭时执行的操作
            console.log('页面已关闭');

            // 其他操作...
        });
        // this.scrollToBottom();
    },
    created() {
        //绑定事件
        window.addEventListener('beforeunload', e => this.closeWebsocket(e))
    },
    beforeDestroy() {
        //卸载事件
        window.removeEventListener('beforeunload', e => this.closeWebsocket(e))
    },
    methods: {
        //滚动到底部
        // 关闭提示
        closeWebsocket(e) {
            if (this.is_open_socket) {
                this.socketTask.close();
                this.is_open_socket = false;
            }
        },
        //获取头像
        cs(obj1) {//重整数组
            // 检查 user 数组中是否存在 obj1.opid
            const _this = this;
            const existingUser = this.user.find(user => user.Open_ID === obj1.Open_ID);
            if (!existingUser) {
                // 如果不存在，则添加新的用户对象到 user 数组
                $.ajax({
                    url: DomainName + '/getInquiryIDAction?token=' + $.cookie("token"),
                    data: {
                        Primary_Key_Name: "OPen_ID",
                        Primary_Key: obj1.Open_ID,
                        Data: "member_info",
                    },
                    complete: function (XMLHttpRequest) {
                        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                        }
                    },
                    success: function (Result) {
                        console.log(Result);
                        const newUser = {
                            Open_ID: obj1.Open_ID,
                            list: [],
                            Seed_Message: "",
                            Image: Result[0].Image,
                            Nick: Result[0].Nick,
                            Enterprise_Info_SerialNumber: Result[0].Enterprise_Info_SerialNumber,
                            Member_SerialNumber: Result[0].Member_SerialNumber,
                            App_ID: Result[0].App_ID
                        };
                        if(obj1.message_type == "system_messages"){
                            newUser.list.push({
                                Message: obj1.Message,                                
                                Time: getYMDHMSDate(),
                                type: 0
                            });
                        }else{
                            newUser.list.push({
                                Message: obj1.userContent,
                                Time: getYMDHMSDate(),
                                type: 0
                            });
                        }
                        

                        _this.user.push(newUser);
                    },
                    dataType: "json"
                });
                console.log(this.user);
            } else {
                // 如果存在，则直接将消息对象添加到对应用户的 list 数组中
                existingUser.list.push({
                    Message:obj1.message_type=='system_messages'?obj1.Message:obj1.userContent,
                    Time:  getYMDHMSDate(),
                    type: 0
                });
            }
        },
        send() {//发送
            let index = this.index;
            let Message = this.user[index].Seed_Message;
            let Open_ID = this.user[index].Open_ID;
            let App_ID = this.user[index].App_ID;
            let Time = getYMDHMSDate();
            //NowTime
            let Enterprise_Info_SerialNumber = this.user[index].Enterprise_Info_SerialNumber;
            if (this.is_open_socket) {
                if (Message != '') {
                    this.user[index].list.push({
                        Message,
                        Time,
                        type: 1
                    })
                    this.socketTask.send(JSON.stringify({
                        Message,
                        Open_ID: Open_ID,
                        Time,
                        type:'serve'
                    }));

                    this.setMessage(Open_ID, Message, Time, App_ID, Enterprise_Info_SerialNumber);
                    this.user[index].Seed_Message = '';
                    this.handle(index);
                } else {
                    this.$message({
                        message: '请输入要发送的消息',
                        type: 'warning'
                    });
                }
            } else {
                this.connectWebsocket();
                if (Message != '') {
                    this.user[index].list.push({
                        Message,
                        Time,
                        type: 1
                    })
                    this.socketTask.send(JSON.stringify({
                        Message,
                        Open_ID: Open_ID,
                        Time
                    }));
                    this.setMessage(Open_ID, Masseg, Message_Time, App_ID, Enterprise_Info_SerialNumber);
                    this.user[index].Seed_Message = '';
                    this.handle(index);
                } else {
                    this.$message({
                        message: '请输入要发送的消息',
                        type: 'warning'
                    });
                }
            }
        },
        handle(index) {//点击联系人
            this.user2 = this.user[index].list;
            this.isShow = true
            this.index = index;
        },
        connectWebsocket() {
            console.log(DomainName.replace('https', 'wss'))
            // 打开一个websocket
            this.socketTask = new WebSocket(DomainName.replace('https', 'wss') + '/websocket?userId=' +
                "WeChat;service;" + $.cookie("use") + ";" + $.cookie("enterprise"));
            // 建立连接
            this.socketTask.onopen = () => {
                // 发送数据
                this.is_open_socket = true;
                console.log("websocket发送数据中");
            };
            // 客户端接收服务端返回的数据
            this.socketTask.onmessage = evt => {
                console.log(JSON.parse(evt.data));
                if (JSON.parse(evt.data).Open_ID !== undefined) {
                    // this.cs(JSON.parse(evt.data));
                }
            };
            // 发生错误时
            this.socketTask.onerror = evt => {
                this.is_open_socket = false;
                console.log("websocket错误：", evt);
            };
            // 关闭连接
            this.socketTask.oncflose = evt => {
                this.is_open_socket = false;
                console.log("websocket关闭：", evt);
            };
        },
        getChatRecords() {
            let that = this
            $.ajax({
                type: 'POST',
                url: DomainName + '/WXMemberServes',
                data: {
                    User_Type: 'service',
                    userid: 'service',
                    Enterprise_Info_SerialNumber: 'E00000000000001',
                },
                success: function (Result) {
                    if (Result.Status == 'success') {
                        that.user = Result.Data
                    }
                },
                dataType: "json"
            });
        },
        getMember(Primary_Key) {
            let that = this
            $.ajax({
                type: 'POST',
                url: DomainName + '/GoodsInquiryKey',
                data: {
                    Data: 'member_info',
                    Primary_Key_Name: 'Open_ID',
                    Primary_Key,
                },
                success: function (Result) {
                    that.user.forEach(item => {
                        if (item.Open_ID == Primary_Key) {
                            item.Image = Result[0].Image
                            item.Nick = Result[0].Nick
                        }
                    })
                },
                dataType: "json"
            });
        },
        setMessage(Open_ID, Messages, Time, App_ID, Enterprise_Info_SerialNumber, Member_Serves_SerialNumber) {
            let table = {
                Member_Serves_SerialNumber: '',
                Open_ID,
                Service_ID: $.cookie("use"),
                Messages,
                Message_Time: Time,
                Open_ID_Type: '0',
                Service_ID_Type: '0',
                App_ID,
                Enterprise_Info_SerialNumber,
                Row_Status: '1'
            };
            $.ajax({
                type: 'POST',
                url: DomainName + '/getAddAction?token=' + $.cookie("token"),
                data: {
                    Data: JSON.stringify({
                        member_serves_info: [table]
                    }),
                },
                success: function (Result) {
                    console.log('发送成功');
                },
                dataType: "json"
            });
        },
    },
})